﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
using INI_RW;

namespace Language
{
    public static class CommLanguageData
    {
        public static LanguageData data = new LanguageData();
    }

    public class LanguageData
    {
        private Hashtable ht = new Hashtable();
        private string CodePageName;
        private Encoding enc;
        public bool enable = false;

        public string CP_Name
        {
            get { return CodePageName; }
        }

        public LanguageData()
        {
            this.enc = Encoding.Default;
            this.CodePageName = enc.WebName;
            this.enable = true;
        }
        public LanguageData(Encoding encoding)
        {
            this.enc = encoding;
            this.CodePageName = enc.WebName;
            this.enable = true;
        }

        public void LoadINI(string LangINIPath)
        {
            if (!Directory.Exists(LangINIPath)) return;
            string LangPath = Path.Combine(LangINIPath, CodePageName + ".ini");
            if (!File.Exists(LangPath)) return;
            IniFile lang_ini = new IniFile(LangPath);
            string[] LangStr = lang_ini.ReadSection(CodePageName);
            if (LangStr.Length > 0)
            {
                RecordCodePage(LangStr);
            }
            else
            {
                LangStr = lang_ini.ReadSection(enc.CodePage.ToString());
                if (LangStr.Length > 0) RecordCodePage(LangStr);
            }

        }

        private void RecordCodePage(string[] LangStr)
        {
            for (int i = 0; i < LangStr.Length; i++)
            {
                int FindS = LangStr[i].IndexOf('='); //尋找第一個出現的索引
                if (FindS > -1)
                {
                    string index = LangStr[i].Substring(0, FindS).Trim();
                    string value = LangStr[i].Substring(FindS + 1, LangStr[i].Length - FindS - 1).Trim();
                    ht[index] = value;
                }
            }
        }
        public string GetString(string key)
        {
            if (key == null) return "";
            if (!enable) return key;
            if (ht[key] == null)
                return key;
            else
                return ht[key].ToString();
        }
    }

}
